<template>
  <div class="login-container">
    <el-form :model="form" status-icon :rules="rules" ref="form" label-width="80px" class="login-form" @keyup.enter.native="submitForm">
      <h2 style="text-align: center; margin-bottom: 30px">登录聊天室</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">进入聊天室</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 构造完整用户对象，不再包含 nickname
          const userData = {
            username: this.form.username,
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 默认头像
            email: `${this.form.username}@example.com`
          };

          // 使用 Vuex 提交登录
          this.$store.dispatch('login', userData);
          this.$router.push('/chat');
        } else {
          console.log('验证失败');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.login-form {
  width: 400px;
  background-color: #ffffff;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>